import { _decorator, Component, EditBox, Label, Node } from 'cc';
import { SocketUtils } from 'db://assets/component/Net/SocketUtils';
const { ccclass, property } = _decorator;

@ccclass('SocketTest')
export class SocketTest extends Component {
    readonly socketUtils: SocketUtils = new SocketUtils();

    @property(Label)
    label: Label = null!;

    @property(Label)
    state: Label = null!;



    @property(EditBox)
    editBox: EditBox = null!;

    start() {}

    connect() {
        this.socketUtils.connect('ws://localhost:3001');
        this.socketUtils.onOpen = () => {
            console.log('WebSocket连接已建立');
        };
        this.socketUtils.onClose = (ev) => {
            console.log('WebSocket连接已关闭，代码：' + ev.code);
        };
        this.socketUtils.onMessage = (data) => {
            console.log('收到消息：' + data);
            this.label.string = data.toString();
        };
        this.socketUtils.onError = (ev) => {
            console.error('WebSocket发生错误：', ev);
        };
    }

    disConnect() {
        if (this.socketUtils && this.socketUtils.isConnected()) {
            this.socketUtils.close();
            console.log('WebSocket已断开连接');
        } else {
            console.error('WebSocket未连接');
        }
    }

    sendTest() {
        if (this.socketUtils && this.socketUtils) {
            this.socketUtils.send(this.editBox.string);
            this.editBox.string = '';
        } else {
            console.error('WebSocket未连接');
        }
    }

    update(deltaTime: number) {}
}
